<?php

class Role extends CI_Controller {
	
	function Role()
	{
		parent::__construct();
		$this->load->model('role_model', '', TRUE);		
		$this->load->model('Home_model', '', TRUE);
		$this->load->model('auth_model', '', TRUE);
	}
	
	function index()
	{
		if ($this->session->userdata('login') == FALSE)
		{
			redirect('auth');
		}

		// Load default view
		$data['title'] = "Role";
		$data['main_view'] = 'role/role_view';
		
		$data['all_role'] = $this->role_model->get_all_role();
		
		// Load view
		$id_role = $this->session->userdata('id_role'); 
		$data['hak_akses0'] = $this->Home_model->get_hak_akses($id_role,0);
		$data['hak_akses1'] = $this->Home_model->get_hak_akses($id_role,1);
		$data['hak_akses2'] = $this->Home_model->get_hak_akses($id_role,2);
		$this->load->view('template', $data);
	}
	
	function add_role(){
	
		$new_role = $this->input->post('nama_role');
		if($new_role != null || $new_role != ""){
			$arr = array(
				'NAMA_ROLE' => $this->input->post('nama_role')
			);
			
			$this->role_model->insert_role($arr);
		}
		
	}
	
	function delete_role(){
		$id = $this->input->post('id_role');
		if($this->role_model->delete_role($id)){
			echo json_encode("true");
		} else echo json_encode("false");
	}
	
	function update_role(){
		$id = $this->input->post('id_role');
		$data['role'] = $this->role_model->get_role($id);
		$this->load->view('role/role_edit', $data);
		
	}
	
	function submit_role(){
		$id = $this->input->post('id_role');
		$arr = array(
			'NAMA_ROLE' => $this->input->post('nama_role')
		);
		
		$this->role_model->update_role($id, $arr);
		
		redirect('role');
	}
	
	function update_hak_akses(){
		$id = $this->input->post('id_role');
		
		$hak_akses_form = $this->input->post('hak_akses_form');
		if($hak_akses_form != "" || $hak_akses_form != null){
			
		} else {
			$id_role_res = $this->auth_model->get_user($id);
			$id_role = $id_role_res->result_array();
		
			$fitur_res = $this->role_model->get_all_fitur();
			$all_fitur = array();
			foreach($fitur_res->result_array() as $fitur){
				$arr_tmp['id_fitur'] = $fitur['ID_FITUR'];
				$arr_tmp['nama_fitur'] = $fitur['NAMA_FITUR'];
				$arr_tmp['status'] = $this->role_model->is_fitur_available($fitur['ID_FITUR'], $id);
				$all_fitur[] = $arr_tmp;
				
			}
			
			$data['all_fitur'] = $all_fitur;
			$data['id_role'] = $id;
			$data['fitur_count'] = $fitur_res->num_rows;
			$this->load->view('role/hak_akses', $data);
		}	
	}
	
	function submit_hak_akses(){
		$id_role = $this->input->post('id_role');echo $id_role;
		$this->role_model->delete_hak_akses($id_role);
		$fitur_arr = explode(',', $this->input->post('id_fitur'));
		foreach($fitur_arr as $arr => $id){
			if (isset($id) && $id != '') {
				$this->role_model->update_hak_akses(
						array(
							'ID_ROLE' => $id_role,
							'ID_FITUR' => $id
						));
			}
		}
	}
}